import EventManager from "./EventManager";
import GameData from "./GameData";

export default class SetDialog extends Laya.Script {

    /** @prop {name:btnClose, type:Node} */
    public btnClose: Laya.Button;

    /** @prop {name:btnChangeLog, type:Node} */
    public btnChangeLog: Laya.Button;

    /** @prop {name:btnLogOut, type:Node} */
    public btnLogOut: Laya.Button;

    /** @prop {name:btnUnbind, type:Node} */
    public btnUnbind: Laya.Button;

    constructor() { super(); }

    onEnable(){
        this.btnClose.on(Laya.Event.CLICK, this, this.onClickClose);
        this.btnChangeLog.on(Laya.Event.CLICK, this, this.onClickChangeLog);
        this.btnLogOut.on(Laya.Event.CLICK, this, this.onClickLogOut);
        this.btnUnbind.on(Laya.Event.CLICK, this, this.onClickUnbind);
    }

    onDisable(): void {
    }


    /**
     * Click:关闭
     */
    onClickClose() {
        (<Laya.View>this.owner).close();
    }

    /**
     * Click:切换账号
     */
    async onClickChangeLog() {
        this.onEventInfo("\n======>切换账号unionlogin(true):");
        let res = await this.onAddCallbackPromise("unionlogin", "true");
        this.onEventInfo(">:unionlogin " + res);
        (<Laya.View>this.owner).close()
    }

    /**
     * Click:取消授权
     */
    async onClickLogOut() {
        this.onEventInfo("\n======>取消授权:");
        let res = await this.onAddCallbackPromise("logout", "");
        this.onEventInfo(">:logout " + res);
        (<Laya.View>this.owner).close()
    }

    /**
     * Click:解绑
     */
    async onClickUnbind() {
        this.onEventInfo("\n======>解绑:");
        let res = await this.onAddCallbackPromise("onUnbind", JSON.stringify(GameData.gamePlayerData));
        this.onEventInfo(">:onUnbind " + res);
        (<Laya.View>this.owner).close()
    }

    onEventInfo(data: string) {
        EventManager.event(EventManager.CONTENT_INFO_CHANGE, data);
    }



    /**
     * 创建一个promise返回
     * @param funName 反射的方法名
     * @param param 传参
     * @returns 
     */
    onAddCallbackPromise(funName: string, param: string): Promise<string> {
        return new Promise((resolve, reject) => {
            let bridge = Laya.Browser.window.PlatformClass.createClass("entry/src/main/ets/AccountDemo");
            bridge.callWithBack((result: string) => {
                resolve(result);
            }, funName, param);
        });
    }


}